package com.stylefeng.guns.common.util;

import com.alibaba.fastjson.JSON;
import com.stylefeng.guns.common.bo.WebuserBo;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;
import com.stylefeng.guns.core.support.RestConstant;
import org.apache.commons.collections.MapUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author carloszhang
 */
public class WebUserKit {

    /**
     * 获取移动端登录用户对象
     * @return
     */
    public static WebuserBo getWebuserBo() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null) {
            throw new GunsException(GunsExceptionEnum.SERVER_ERROR);
        }
        WebuserBo webuserBo = (WebuserBo) request.getAttribute(RestConstant.USER_INFO_KEY);
        if (webuserBo == null || webuserBo.getId() == null || webuserBo.getId().intValue() == 0) {
            throw new GunsException(BizExceptionEnum.USER_NOT_LOGIN);
        }
        return webuserBo;
    }

    /**
     * 获取移动端登录用户的id
     * @return
     */
    public static int getWebUserId() {
        WebuserBo userInf = getWebuserBo();
        return userInf.getId();
    }

    public static HttpServletRequest getHttpRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static String requestToJson(HttpServletRequest request) {
        Map requestParams = request.getParameterMap();
        Map<String, String> data = new HashMap<>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            data.put(name, valueStr);
        }
        if (MapUtils.isEmpty(data))
            return null;
        return JSON.toJSONString(data);
    }
}
